package com.grandtech.insurance.common.oss;

import com.grandtech.insurance.common.R2;
import com.grandtech.insurance.feign.OssFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class AliOssURL {

    @Autowired(required = false)
    private OssFeignService ossFeignService;

    private static AliOssURL ossURL;

    @PostConstruct //@PostConstruct修饰的方法会在服务器加载Servle的时候运行，并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行
    public void init() {
        ossURL = this;
        ossURL.ossFeignService = this.ossFeignService;
    }

    // @PostConstruct
    public static String url(AliOssClientParamDO aliOssClientParamDO, String key) {
        try {
            if (aliOssClientParamDO == null || key == null) {
                return "";
            }
            Integer ossType = OssType.type;
            if (ossType == 0) {
                return AliOssClientUtils.generateUrl(aliOssClientParamDO, key);
            } else {
                R2<String> res = ossURL.ossFeignService
                        .url(aliOssClientParamDO.getEndpoint(), aliOssClientParamDO.getBucketName(),
                                aliOssClientParamDO.getAccessKeyId(), key, ossType);
                if (res == null) {
                    return "";
                }
                return res.getData();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

}
